// pages/address/address.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: [],
    radio: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  onShow() {
    console.log('onshow')
    this.fetchList()
  },
  fetchList() {
    db.collection('mock_address').get().then(res => {
      this.setData({
        address: res.data,
        radio: res.data.find(item => item.isDefault)?._id
      })
    })
  },
  onEdit(e) {
    wx.navigateTo({
      url: '/pages/address-detail/address-detail?id=' + e.currentTarget.dataset.id,
    })
  },

  onChange(e) {
    console.log(e)
    wx.cloud.callFunction({
      name: 'changeDefault',
      data: {
        id: e.detail
      }
    }).then(res => {
      this.fetchList()
    })
  },
  onRemove(e){
    db.collection('mock_address').doc(e.currentTarget.dataset.id).remove().then(res => {
      wx.showToast({
        title: '删除成功',
      })
      this.fetchList()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },
  onAdd() {
    wx.navigateTo({
      url: '/pages/address-detail/address-detail',
    })
  }
})